package com.lin.missyou.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.missyou.exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.AttributeConverter;
import java.util.HashMap;
import java.util.Map;

/**
 * Json转换
 * @author gcq
 * @Create 2021-10-17
 */
@Component
public class MapAndJson implements AttributeConverter<Map<String, Object>, String> {

    @Autowired
    ObjectMapper mapper;

    /**
     * 转换成数据库中的列
     * @param attribute
     * @return
     */
    @Override
    public String convertToDatabaseColumn(Map<String, Object> attribute) {
        try {
            return mapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new ServerErrorException(9999);
        }
    }

    /**
     * 将字符串转换成实体属性
     * @param s
     * @return
     */
    @Override
    public Map<String, Object> convertToEntityAttribute(String s) {
        try {
            return mapper.readValue(s, HashMap.class);
        } catch (JsonProcessingException e) {
            throw new ServerErrorException(9999);
        }
    }
}